<?php
/**
 * Object Relational Persistence Mapping Class for table: patient_medical_agent
 *
 * @package	com.clearhealth
 * @author	ClearHealth Inc.
 */

class PatientMedicalAgent extends ORDataObject {

	/**#@+
	 * Fields of table: patient_medical_agent mapped to class members
	 */
	var $id		= '';
	var $patient_id		= '';
	var $medical_agent_id		= '';
	var $value		= '';
	var $input_person = '';
	var $updated = '';
	/**#@-*/

	/**
	 * DB Table
	 */
	var $_table = 'patient_medical_agent';

	/**
	 * Primary Key
	 */
	var $_key = 'id';
	
	/**
	 * Internal Name
	 */
	var $_internalName = 'PatientMedicalAgent';

	/**
	 * Handle instantiation
	 */
	function PatientMedicalAgent() {
		parent::ORDataObject();
	}
	
	public function getUpdated($format='%d/%m/%Y') {
		return $this->getLocalizedDate('updated');
	}
	
	public function getUpdaterName() {
		$sql = "SELECT name FROM person WHERE person_id = $this->input_person";
		$res = $this->_execute($sql);
		return $res->fields['name'];
	}
	
	public function getPatientIssues($patientId) {
	    $field        =   L10nHelper::changeField(L10nHelper::getLocale(), 'name');
		$format	=	L10nHelper::getSqlDateFormat();		
		$ds 	= 	new Datasource_sql();
		$sql	= 	array(
			'cols' 		=> "id, ma.$field as name, REPLACE(value, '\n', '<br>') AS value, p.name as person_name, DATE_FORMAT(updated,'$format') as updated",
			'from' 		=> "$this->_table AS pma 
			            LEFT JOIN medical_agent AS ma ON pma.medical_agent_id = ma.medical_agent_id 
						LEFT JOIN person p ON pma.input_person = p.person_id",
			'where' 	=> "patient_id = $patientId"
			);
					
		$ds->setup($this->_db, $sql);
		return $ds->toArray();
	}
	
	public function addNewIssue($patientId, $issueId, $issueValue, $inputPerson, $updated='') {
		if ($updated == '') {
			$updated = date('Y-m-d');
		}
		$data = array (
				'medical_agent_id' => $issueId,
		        'patient_id'       => $patientId,
				'value'		       => $issueValue,
				'input_person'     => $inputPerson,
				'updated'          => $updated
			);		
		$this->populateArray($data);		
		return $this->persist();
	}
	
	public function getId($patientId, $issueId) {
		$sql = "SELECT id FROM $this->_table WHERE patient_id = $patientId AND medical_agent_id = $issueId";
		$res = $this->_execute($sql);
		if(!empty($res) && ($res->fields['id'] != '')) {
			return $res->fields['id'];
		}
		return 0;
	}
	
	public function deleteIssue($id) {
		$sql = "DELETE FROM $this->_table WHERE id = $id";
		$this->_execute($sql);
	}
	
	public function getRealPersistenceInfo() {
		$sql = "SELECT REPLACE(value, '\n', '<br>') AS value FROM $this->_table WHERE $this->_key = $this->id";
		$res = $this->_execute($sql);
		return $res->fields['value'];
	}
}
?>
